<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Input;
use App\Models\Role;
use App\Models\Menu;
use App\Models\Access;

class RoleController extends BaseController{
	
	public function getIndex(){
		
		return view('role.index');
	}
	
	//返回DataTable
	public function getDatatable(){
        $dt=array();
        $orderby = isset( $_GET[ 'order'  ] ) ? $_GET[ 'columns' ][ $_GET[ 'order' ][ 0 ][ 'column' ] ][ 'name' ] : 'id';
        $orderdir = isset( $_GET[ 'order'  ] ) ? $_GET[ 'order' ][ 0 ][ 'dir' ] : 'asc';
        $start = Input::get('start',0);//从多少开始
        $length = Input::get('length',10);//数据长度
        $search = $_GET['search']['value'];//搜索获取前台传过来的过滤条件
        $recordsTotal = Role::count();
        $where='1=1 ';
        if($search!=''){
        	$where.='and name like "%'.$search.'%"';
        }
        $data = Role::whereRaw($where)->select('id', 'name','status_at')->skip($start)->take($length)->orderBy($orderby,$orderdir)->get();
        $recordsFiltered=  Role::whereRaw($where)->count();
        $datatable=array();
        $isset='';
        $iseditstr='';
        $isdelstr='';
        if (\Gate::check('chkaccess', 'App\Http\Controllers\RoleController@getSet')) {
        	$isset='<button class="btn-white btn btn-xs" onclick="location.href=\'/role/set/$reset\'">权限设置</button>';
        }
        if (\Gate::check('chkaccess', 'App\Http\Controllers\RoleController@getEdit')) {
         	$iseditstr='        <button class="btn-white btn btn-xs" onclick="location.href=\'/role/edit/$reeditstr\'">编辑</button>';
        }
        if (\Gate::check('chkaccess', 'App\Http\Controllers\RoleController@postDel')) {
        	$isdelstr='<button class="btn-white btn btn-xs" onclick="singledel(\'/role/del\',$redelstr);">删除</button>';
        }
        foreach ($data as $item) {
        	$status_at=$item->status_at==1?'<span class="label label-primary">启用</span>':'<span class="label label-danger">禁用</span>';
            $obj=array('<input type="checkbox" name="chk" value='.$item->id.' />',$item->id,$item->name,$status_at,str_replace('$reset',$item->id,$isset).str_replace('$reeditstr',$item->id,$iseditstr).str_replace('$redelstr',$item->id,$isdelstr));
            array_push($datatable,$obj);
        }
        $dt['draw']=intval(Input::get('draw',0));
        $dt['data']=$datatable;
        $dt['recordsTotal']=$recordsTotal;
        $dt['recordsFiltered']=$recordsFiltered;
        // $dt['error']='暂时没有数据';
        echo json_encode($dt);     
    }


	public function getAdd(){
		return view('role.add');
	}

	public function postAdd(){
		\Input::merge(array_map('trim', \Input::all()));
		$name=Input::get('name');
		$role = new Role;
		$role->name = $name;
		$isExist=Role::where('name',$name)->first();
		if($isExist){
			return redirect('tooltip/failure')->with(['redirectway'=>'角色已存在','redirecturl'=>'/role/index']);
		}
		$res=$role->save();
		if($res){
			return redirect('tooltip/success')->with(['redirectway'=>'添加成功！','redirecturl'=>'/role/index']);
		}else{
			return redirect('tooltip/failure')->with(['redirectway'=>'添加失败！','redirecturl'=>'/role/index']);
		}
	}
	
	public function getEdit($id){
		$info = Role::find($id);
		return view('role.edit')->with('info',$info);
	}

	public function postEdit(){
		\Input::merge(array_map('trim', \Input::all()));
		$role = Role::find(Input::get('id'));
		$isExist=Role::where('id','<>',Input::get('id'))->where('name',Input::get('name'))->first();
		if($isExist){
			return redirect('tooltip/failure')->with(['redirectway'=>'角色已存在','redirecturl'=>'/role/index']);
		}
		$role->name = Input::get('name');
		$res=$role->save();
		if($res){
			return redirect('tooltip/success')->with(['redirectway'=>'修改成功！','redirecturl'=>'/role/index']);
		}else{
			return redirect('tooltip/failure')->with(['redirectway'=>'修改失败！','redirecturl'=>'/role/index']);
		}
	}

	public function postDel(){
		$res=Role::destroy(Input::get('data'));
		if($res){
			die('1');
		}
		else{
			die('0');
		}
	}

	public function getSet($role_id){
		$html_tree='';
		$accesscol=Access::all();
		$access=$accesscol->toArray();

		$mlv1=Menu::where('status_at',1)->where('pid',1)->where('level',1)->orderBy('sort', 'asc')->get();
		foreach ($mlv1 as $key=>$value){
			$checked=($this->is_checked($role_id,$value->id,$access))? "checked='checked'": '';
			$html_tree.="<tr><td width='150'><div class='checkbox'><input id='chk".$value['id']."' type='checkbox' level='1' name='menu_id[]' ".$checked." value='".$value['id']."' onclick='javascript:checknode(this);'/><label for=chk".$value['id'].">".$value['name']."</label></div></td><td colspan='2'></td></tr>";
			$mlv2=Menu::where('status_at',1)->where('pid',$value['id'])->where('level',2)->orderBy('sort', 'asc')->get();
			foreach ($mlv2 as $val)
			{
				$checked=($this->is_checked($role_id,$val->id,$access))?"checked='checked'": '';
				$html_tree.="<tr><td></td><td width='150'><div class='checkbox'><input id='chk".$val['id']."' type='checkbox' level='2' name='menu_id[]' ".$checked." value='".$val['id']."' onclick='javascript:checknode(this);'/><label for=chk".$val['id'].">".$val['name']."</label></div></td><td><ul class='list-inline'>";
				$mlv3=Menu::where('status_at',1)->where('pid',$val->id)->where('level',3)->orderBy('sort', 'asc')->get();
				foreach ($mlv3 as $v)
				{
					$checked=($this->is_checked($role_id,$v->id,$access))?"checked='checked'": '';
					$html_tree.="<li><div class='checkbox'><input id='chk".$v['id']."' type='checkbox' level='3' name='menu_id[]' ".$checked." value='".$v['id']."' onclick='javascript:checknode(this);'/><label for=chk".$v['id'].">".$v['name']."</label></div></li>";
				}
				$html_tree.="</ul></td></tr>";
			}
		}
		return view('role.set')->with(['html_tree'=>$html_tree,'role_id'=>$role_id]);

	}

	public function postSet(){
			$role_id=Input::get('role_id');
			$menu_id=Input::get('menu_id');
			if (!$menu_id) {
				return redirect('role/set')->with(['redirectway'=>'修改失败！','redirecturl'=>'/role/index']);
			}
			$data=array();
			if (is_array($menu_id) && count($menu_id) > 0) {  //提交得有数据，则修改原权限配置
				Access::where('role_id',$role_id)->delete();
				$menu=Menu::where('status_at',1)->orderBy('sort', 'asc')->get();
				foreach ($menu as $v)$menu[$v->id] = $v;
						foreach($menu_id as $k => $v){
						
							$data[$k]['menu_id']=$v;
							$data[$k]['role_id'] = $role_id;
						}


			
				\DB::table('access')->insert($data);
				
			} else {    //提交的数据为空，则删除权限配置
				Access::where('role_id',$role_id)->delete();
			}
			return redirect('tooltip/success')->with(['redirectway'=>'权限设置成功！','redirecturl'=>'/role/index']);
	}

	private function is_checked($role_id,$menu_id,$access) {
		$nodetemp = array('role_id' =>$role_id,'menu_id' =>$menu_id);
		$isExist = in_array($nodetemp, $access);
		if($isExist){
			return true;
		} else {
			return false;
		}
	}

}
